package cn.yhp.gateway.session.handlers;

import cn.yhp.gateway.session.BaseHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**会话服务处理
 * @author yhp
 * @description
 * @date 2024/5/6
 */
public class SessionServerHandler extends BaseHandler<FullHttpRequest> {

    private final Logger logger= LoggerFactory.getLogger(SessionServerHandler.class);
    @Override
    protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest msg) {
        logger.info("网关接收请求，url:{},method:{}",msg.uri(),msg.method());

        // 返回信息处理
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        // 返回信息处理
        response.content().writeBytes(JSON.toJSONBytes("你访问路径被mou网关管理了 URI：" + msg.uri(),
                SerializerFeature.PrettyFormat));
        // 头部信息设置
        HttpHeaders headers = response.headers();
        // 响应类型，长度，持久连接
        headers.add(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.APPLICATION_JSON+"; charset=UTF-8");
        headers.add(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
        headers.add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);

        // 跨域配置
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        channel.writeAndFlush(response);

    }
}
